package top.zhaoyuliu.logbook.client.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import top.zhaoyuliu.logbook.client.link.LinkObject;
import top.zhaoyuliu.logbook.client.link.LinkThreadLocal;
import top.zhaoyuliu.logbook.client.queue.LbQueue;

/**
 * Copyright © 2021 Arain. All rights reserved.
 *
 * @Title: LinkAspect.java
 * @Prject: logbook-client
 * @Package: top.zhaoyuliu.logbook.client.aspect
 * @Description: <功能详细描述>
 * @author: Arain
 * @date: 2021年1月22日 下午8:03:48
 * @version: V1.0
 */
@Aspect
@Component
@Order(1)
public class LinkAspect {

//	@Pointcut("@annotation(top.zhaoyuliu.logbook.client.annotation.Link) || execution(* *..*Controller.*(..)) || execution(* *..*ServiceImpl.*(..)) || execution(* *..*Dao.*(..))")
	@Pointcut("@annotation(top.zhaoyuliu.logbook.client.annotation.Link) || execution(* *..support.module.*..*(..))")
	public void logAspect() {
	}

	@Around("logAspect()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		long startTime = System.currentTimeMillis();
		LinkObject object = LinkThreadLocal.threadLocal.get();
		String traceId = LinkThreadLocal.traceID.get();
		if (object == null) {
			object = new LinkObject();
			object.getHierarchy().set(0);
		}
		object.setTrackId(traceId);
		object.getHierarchy().incrementAndGet();
		object.setMethed(joinPoint.getSignature().toString());
		LinkThreadLocal.threadLocal.set(object);
		Object proceed = joinPoint.proceed();
		object.getHierarchy().incrementAndGet();
		object.setMethed(joinPoint.getSignature().toString());
		long endTime = System.currentTimeMillis();
		object.setProceTime(endTime - startTime);
		object.setMessageId(IdUtil.getSnowflake(1L, 1L).nextId());
		String jsonStr = JSONUtil.toJsonStr(object);
		LbQueue.pushtrackQueue(jsonStr);
		return proceed;
	}

//	@Before("logAspect()")
//	public void before(JoinPoint joinPoint) {
//		String traceId = LinkThreadLocal.traceID.get();
//		HttpServletRequest request = RequestUtils.getCurrentRequest();
//		ParameterLbBuilder parameterLbBuilder = new ParameterLbBuilder(request.getRequestURL().toString(),
//				request.getMethod(), request.getRemoteAddr(), JSONUtil.toJsonStr(request.getParameterMap()));
//		parameterLbBuilder.setTrackId(traceId);
//		LbQueue.pushParaQueue(JSONUtil.toJsonStr(parameterLbBuilder));
//	}
}
